<?php

namespace ApiBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Filesystem\Filesystem;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class BaseController extends Controller
{

    protected $salt;

    protected $response;
    protected $user_id;
    protected $admin_response;
    protected $admin_id;
    protected $plat_response;
    protected $plat_id;
    protected $district_id;

    // 发送短信类型
    const SMS_UNKNOWN = 0; // 未知 不做任何处理
    const SMS_USER_REGISTER = 1; // 无名片注册
    const SMS_USER_FORGET_PASSWORD = 2;  // 用户端 找回密码
    const SMS_ADMIN_FORGET_PASSWORD = 3; // 管理员端 找回密码
    const SMS_PLATFORM_ADMIN_FORGET_PASSWORD = 4; // 平台管理员端 找回密码


    /**
     * 判断登录
     *
     * @param $conn
     * @return bool
     */
    public function isLogged($conn = null)
    {
        $conn = $conn ?: $this->get('database_connection');

        $token = $this->get('request')->get('token');
        $user = $conn->fetchAssoc("SELECT * FROM user WHERE token = '". $token ."' LIMIT 1");
        if (!$user) {
            $this->response = $this->jsonResponse(-1, '未登录');
            return false;
        }

        $this->user_id = $user['id'];

        return true;
    }

    /*
     * 获取用户id
     */
    public function getUserId()
    {
        return $this->user_id;
    }

    /*
     * 管理员端  判断登录
     */
    public function isAdminLogged()
    {
        $conn = $this->get("database_connection");

        $platform = $this->get("request")->get("platform");

        $is_app = in_array($platform,array("weixin"));


        if($is_app){

            $admin_token = $this->get("request")->get("token");
            $admin = $conn->fetchAssoc("SELECT * FROM admin WHERE token = '". $admin_token ."'");
        }


        if(!$is_app){

            $session_admin_id = $this->get("session")->get("admin_id");

            $admin = $conn->fetchAssoc("SELECT * FROM admin WHERE id = '". $session_admin_id ."'");

        }

        if(!$admin){
            $this->admin_response = $this->jsonResponse(-1,"未登录");
            return false;
        }



        $this->admin_id = $admin['id'];
        $this->district_id = $admin['district_id'];

        $this->get("session")->set("admin_id",$admin['id']);
        $this->get("session")->set("admin_name",$admin['realname']);
        $this->get("session")->set("admin_role_id",$admin['admin_role_id']);
        $this->get("session")->set("district_id",$admin['district_id']);
        return true;
    }

    public function getAdminId(){
        return $this->admin_id;
    }

    public function getDistrictId(){
        return $this->district_id;
    }

    public function isPlatAdminLogged()
    {
        $conn = $this->get("database_connection");
        $plat_admin_id = $this->get("session")->get("plat_id");
        $plat_admin = $conn->fetchAssoc("SELECT * FROM admin WHERE id = '". $plat_admin_id ."' AND admin_role_id = 1");
        if(!$plat_admin){
            $this->plat_response = $this->jsonResponse(-1,"未登录");
            return false;
        }

        $this->plat_id = $plat_admin['id'];

        $this->get("session")->set("plat_id",$plat_admin['id']);
        $this->get("session")->set("plat_name",$plat_admin['realname']);
        return true;

    }

    public function getPlatId(){
        return $this->plat_id;
    }



    /**
     * json数据返回封装
     *
     * @param $errorCode
     * @param $message
     * @param array $data
     * @return JsonResponse
     */
    protected function jsonResponse($errorCode, $message = '', $data = array())
    {
        $result = ['errorCode' => $errorCode, 'message' => $message, 'data' => $data];

        return new JsonResponse($result);
    }

    /**
     * json数据返回失败
     *
     * @param $data
     * @param string $message
     * @return JsonResponse
     */
    protected function jsonResponseSuccess($data, $message = '')
    {
        return $this->jsonResponse(0, $message, $data);
    }

    /**
     * json数据返回失败
     *
     * @param string $message
     * @return JsonResponse
     */
    protected function jsonResponseFailure($message = '')
    {
        return $this->jsonResponse(1, $message);
    }

    /**
     * 跳转到页面
     *
     * @param string $redirect_url
     * @param string $route_name
     * @return RedirectResponse
     */
    public function redirectUrl($route_name = '', $redirect_url = '')
    {
        $param = $redirect_url ? ['redirect_url' => $redirect_url] : [];

        return $this->redirectToRoute($route_name, $param);
    }

    /**
     * 微信端调用其他bundle数据
     *
     * @param $BundleControllerAction
     * @param array $path
     * @return mixed
     */
    public function getApiData($BundleControllerAction, array $path = array())
    {
        $data = $this->forward($BundleControllerAction, $path)->getContent();

        return json_decode($data, TRUE);
    }

    /**
     * 上传图片
     *
     * @param $inputName 这个是表单上file类型的input的name值
     * @param $path 图片上传路径
     * @param $filename 图片名称，不包括扩展名
     * @param array $format 图片类型
     * @param int $size 图片尺寸
     * @return array 图片的全名，包括扩展名
     */
    public function uploadImage($inputName, $path, $filename, $format = array('image/png', 'image/gif', 'image/jpg', 'image/jpeg'), $size = 2)
    {
        $result = array();
        $result['errors'] = array('上传失败');
        $path_absolute = $this->get('kernel')->getRootDir() . '/../web/' . $path;
        if (!file_exists($path_absolute)) {
            mkdir($path_absolute, 0755);
        }

        $storage = new \Upload\Storage\FileSystem($path);
        $file = new \Upload\File($inputName, $storage);

        if ($file->getSize() > $size * 1024 * 1024) {
            $result['errors'] = array('上传图片不得超过' . $size . 'M');
        } else {
            if ($file->getName() != '') {//有新的图片上传
                $file->setName($filename);

                // Validate file upload
                // MimeType List => http://www.webmaster-toolkit.com/mime-types.shtml
                $file->addValidations(array(
                    // new \Upload\Validation\Mimetype($format),
                    new \Upload\Validation\Size($size . 'M')
                ));

                try {
                    $file->upload();
                    $result['path'] = $path . $file->getNameWithExtension();
                    $result['size'] = $file->getSize();
                    $result['origin_name'] = $_FILES[$inputName]['name'];
                    $result['created_at'] = date('Y-m-d H:i:s');
                } catch (\Exception $e) {
                    $result['errors'] = $file->getErrors();
                }
            }
        }

        return $result;
    }

    /**
     * 发送短信
     *
     * @param $phone
     * @param $content
     * @param $sendtime
     * @return array
     */
    public function send($phone, $salt, $type)
    {

        if($type == 5){

            $send_url = "http://v.juhe.cn/sms/send?mobile=". $phone ."&tpl_id=41974&tpl_value=". $salt ."&key=4cf95984b2f90445660371a923544d70";

        } else {
            $send_code = "#code#=" . $salt;
            $send_url = "http://v.juhe.cn/sms/send?mobile=". $phone ."&tpl_id=41972&tpl_value=". urlencode($send_code) ."&key=4cf95984b2f90445660371a923544d70";
        }

        $this->curl($send_url);
    }

    /**
     * 发送短信处理
     *
     * @param $phone
     * @param $type
     * @param $role
     * @return null|string
     */
    public function sendMessage($phone, $type, $role)
    {
        //发送短信次数及时间间隔
        if($type != 5){
            $error = $this->checkSMSRecord($phone, $type, $role);
            if ($error) {
                return $error;
            }
        }


        $salt = $this->get('helper.strings')->generateSalt(4);

//        switch ($type) {
//            case self::SMS_USER_REGISTER:
//                $content = '您的验证码是：' . $salt . '，2分钟有效，请勿告诉他人。';
//                break;
//            case self::SMS_USER_FORGET_PASSWORD:
//                $content = '您的验证码是：' . $salt . '，2分钟有效，请勿告诉他人。';
//                break;
//            case self::SMS_ADMIN_FORGET_PASSWORD:
//                $content = '您的验证码是：' . $salt . '，2分钟有效，请勿告诉他人。';
//                break;
//            case self::SMS_PLATFORM_ADMIN_FORGET_PASSWORD:
//                $content = '您的验证码是：' . $salt . '，2分钟有效，请勿告诉他人。';
//                break;
//            default:
//                $content = '';
//                break;
//        }

//        if ( empty($content) ) {
//            return NULL;
//        }

        // 发送短信
        $this->send($phone,$salt,$type);

        if($type != 5){
            $data = array(
                'phone' => $phone,
                'salt' => $salt,
                'happen_time' => time(),
                'type' => $type,
                'role' => $role,
                'times' => 0,
                'is_used' => 0,
                'ip' => $this->get('request')->getClientIp()
            );

            $this->get('database_connection')->insert('sms_record', $data);

        }
        $this->salt = $salt;

        return NULL;
    }

    /**
     * 检测短信发送次数及间隔时间
     *
     * @param $phone
     * @param int $type
     * @param $role
     * @return null|string
     */
    public function checkSMSRecord($phone, $type = 0, $role)
    {
        $error = NULL;
        $day = strtotime(date('Y-m-d'));
        $record = $this->get('database_connection')->fetchAssoc('SELECT COUNT(*) AS count, happen_time FROM sms_record WHERE phone = ? AND type = ? AND role = ? AND happen_time > ? ORDER BY happen_time DESC', array($phone, $type, $role, $day));

        //每天发送5次短信
        if (!empty($record['count']) && $record['count'] > 5) {
            $error = '获取验证码次数过多！';
        } else {
            $time = time();
            //每次发送短信间隔不能少于2分钟
            if (!empty($record['happen_time']) && $time - $record['happen_time'] < 60) {
                $error = '获取验证码间隔时间为1分钟！';
            }
        }

        return $error;
    }

    /**
     * 短信验证码验证（有效期、验证次数、是否使用等）
     *
     * @param $phone
     * @param $salt
     * @param int $type
     * @param $role
     * @return string
     */
    public function checkSMSSalt($phone, $salt, $type = 0, $role)
    {
        $error = '';
        $conn = $this->get('database_connection');
        $record = $conn->fetchAssoc('SELECT id, happen_time, times, is_used, salt FROM sms_record WHERE phone = ? AND type = ? AND role = ? ORDER BY happen_time DESC LIMIT 1', array($phone, $type, $role));

        if (empty($record)) {
            $error = '请先获取验证码！';
        } else {
            if ($record['salt'] != $salt) {
                $error = '验证码错误！';
                $conn->executeUpdate('UPDATE sms_record SET times = times + 1 WHERE id = ?', array($record['id']));
            } elseif(time() - $record['happen_time'] > 1800) { //验证码有效期30分钟
                $error = '验证码已失效！';
            } elseif ($record['times'] > 5) { //验证码验证次数5次
                $error = '验证次数过多！';
            } elseif ($record['is_used']) {
                $error = '验证码已使用过！';
            } else {

                $conn->executeUpdate('UPDATE sms_record SET is_used = 1 WHERE id = ?', array($record['id']));
            }
        }

        return $error;
    }

    public function checkPhoneExit($phone){
        $conn = $this->get("database_connection");
        $user = $conn->fetchColumn("SELECT count(*) FROM user WHERE phone ='". $phone ."'");
        $admin = $conn->fetchColumn("SELECT count(*) FROM admin WHERE phone ='". $phone ."'");

        return $user + $admin;

    }

    /*
     * 聚合数据
     */
    function curl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        $output = curl_exec($ch);

        curl_close($ch);

        return json_decode($output);
    }

    /*
     * 插入企业数据
     *
     *
     */
     function insertCompany($new_company){
         $add_data = array(
             "name" => $new_company->result->enterpriseName,
             "fr_name" => $new_company->result->frName,
             "reg_cap" => $new_company->result->regCap,
             "credit_code" => $new_company->result->creditCode,
             "enterprise_status" => $new_company->result->enterpriseStatus,
             "enterprise_type" => $new_company->result->enterpriseType,
             //"es_date" => $new_company->result->esDate,
             //"open_from" => $new_company->result->openFrom,
             //"open_to" => $new_company->result->openTo,
             "address" => $new_company->result->address,
             "operate_scope" => $new_company->result->operateScope,
             "created_at" => date('Y-m-d H:i:s')
//                    "admin_id",
//                    "company_attribute_id",
//                    "company_category_id",
//                    "trade_mark",
//                    "district_id"
         );

//         $add_data['es_date'] = "";
         if($this->is_Date($new_company->result->esDate)){

             $add_data['es_date'] = $new_company->result->esDate;
         }

//         $add_data['open_from'] = "";
         if($this->is_Date($new_company->result->openFrom)){

             $add_data['open_from'] = $new_company->result->openFrom;
         }

//         $add_data['open_to'] = "";
         if($this->is_Date($new_company->result->openTo)){

             $add_data['open_to'] = $new_company->result->openTo;
         }

         return $add_data;
     }

    /*
     *  插入专利数据
     *  $pantent_arr 专利json数据  聚合数据获取
     *  $new_company_id 企业id
     *
     */
    function insertPatent($pantent_arr,$new_company_id){
        $insert_pantent = array(
            "company_id" => $new_company_id,
            //"patent_title" => $pantent_arr->title,
            //"patent_id" => $pantent_arr->id,
            //"application_number" => $pantent_arr->applicationNumber,
            //"patent_type" => $pantent_arr->type,
            //"application_date" => $pantent_arr->applicationDate,
            //"main_ipc" => $pantent_arr->mainIpc,
            //"applicant" => $pantent_arr->applicant,
            //"summary" => $pantent_arr->summary,

//            "patent_id" => $pantent_arr['title'],
//            "application_number" => $pantent_arr['applicationNumber'],
//            "patent_type" => $pantent_arr['type'],
//            "application_date" => $pantent_arr['applicationDate'],
//            "main_ipc" => $pantent_arr['mainIpc'],
//            "applicant" => $pantent_arr['applicant'],
//            "summary" => $pantent_arr['summary'],

            //"created_at" => date('Y-m-d H:i:s')
        );

        if(isset($pantent_arr->title)){
            $insert_pantent['patent_title'] = $pantent_arr->title;
        }

        if(isset($pantent_arr->id)){
            $insert_pantent['patent_id'] = $pantent_arr->id;
        }
        if(isset($pantent_arr->applicationNumber)){
            $insert_pantent['application_number'] = $pantent_arr->applicationNumber;
        }
        if(isset($pantent_arr->type)){
            $insert_pantent['patent_type'] = $pantent_arr->type;
        }

        if(isset($pantent_arr->applicationDate)){
            $insert_pantent['application_date'] = $pantent_arr->applicationDate;
        }

        if(isset($pantent_arr->mainIpc)){
            $insert_pantent['main_ipc'] = $pantent_arr->mainIpc;
        }

        if(isset($pantent_arr->applicant)){
            $insert_pantent['applicant'] = $pantent_arr->applicant;
        }

        if(isset($pantent_arr->summary)){
            $insert_pantent['summary'] = $pantent_arr->summary;
        }


        return $insert_pantent;
    }

    /*
   *  插入专利数据
   *  $pantent_arr 专利json数据  聚合数据获取
   *  $new_company_id 企业id
   *
   */
    function insertPatentArray($pantent_arr,$new_company_id){


        $insert_pantent = array(
            "company_id" => $new_company_id,

            "patent_id" => $pantent_arr['title'],
            "application_number" => $pantent_arr['applicationNumber'],
            "patent_type" => $pantent_arr['type'],
            "application_date" => $pantent_arr['applicationDate'],
            "applicant" => $pantent_arr['applicant'],
            "summary" => $pantent_arr['summary'],

            "created_at" => date('Y-m-d H:i:s')
        );

        if(isset($pantent_arr['mainIpc'])){
            $insert_pantent['main_ipc'] = $pantent_arr['mainIpc'];
        }

        return $insert_pantent;
    }

    /**
     * 获取图片的Base64编码(不支持url)
     * @date 2017-02-20 19:41:22
     *
     * @param $img_file 传入本地图片地址
     *
     * @return string
     */
    function imgToBase64($img_file) {

        $img_base64 = '';
        if (file_exists($img_file)) {
            $app_img_file = $img_file; // 图片路径
            $img_info = getimagesize($app_img_file); // 取得图片的大小，类型等

            //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
            $fp = fopen($app_img_file, "r"); // 图片是否可读权限

            if ($fp) {
                $filesize = filesize($app_img_file);
                $content = fread($fp, $filesize);
                $file_content = chunk_split(base64_encode($content)); // base64编码
                switch ($img_info[2]) {           //判读图片类型
                    case 1: $img_type = "gif";
                        break;
                    case 2: $img_type = "jpg";
                        break;
                    case 3: $img_type = "png";
                        break;
                }

                $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码

            }
            fclose($fp);
        }

        return $img_base64; //返回图片的base64
    }

    function base64EncodeImage ($image_file) {
        $base64_image = '';

        $img_dir = $this->container->get('kernel')->getRootDir() . '/../web/' . $image_file;
        $image_info = getimagesize($img_dir);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
//        $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));

        $base64_image = chunk_split(base64_encode($image_data));
        return $base64_image;
    }


    /**
     * 发邮件
     */
    function emailAction($addEmail)
    {
        // TODO 简易板http://www.w3school.com.cn/php/php_mail.asp

        // TODO 复杂的要调用类库 PHPMailer 位置:/var/www/html/PHPMailer-master.zip
        // composer.json "phpmailer/phpmailer": "~6.0" 或者 执行 composer require phpmailer/phpmailer

        //Create a new PHPMailer instance
                $mail = new PHPMailer;
        //Tell PHPMailer to use SMTP
                $mail->isSMTP();
        //Enable SMTP debugging
        // 0 = off (for production use)
        // 1 = client messages
        // 2 = client and server messages
                $mail->SMTPDebug = 2;
        //Set the hostname of the mail server
                $mail->Host = 'smtp.126.com';
        // use
        // $mail->Host = gethostbyname('smtp.gmail.com');
        // if your network does not support SMTP over IPv6
        //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
                $mail->Port = 465;
        //Set the encryption system to use - ssl (deprecated) or tls
                $mail->SMTPSecure = 'ssl';
        //Whether to use SMTP authentication
                $mail->SMTPAuth = true;
        //Username to use for SMTP authentication - use full email address for gmail
                $mail->Username = "ksnd57559014@126.com";
        //Password to use for SMTP authentication
                $mail->Password = "mb5700906"; // 授权码 第一次使用记得生成 每次更新记得更换
        //Set who the message is to be sent from
                $mail->setFrom('ksnd57559014@126.com', '昆山高新区科技局');
        //Set an alternative reply-to address
        //        $mail->addReplyTo('replyto@example.com', 'First Last');
        //Set who the message is to be sent to
                $mail->addAddress($addEmail);
        //Set the subject line
                $mail->Subject = 'PHPMailer GMail SMTP test';
        //Read an HTML message body from an external file, convert referenced images to embedded,
        //convert HTML into a basic plain-text alternative body
                $mail->msgHTML('Hello world!');
        //        $mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
        //Replace the plain text body with one created manually
                $mail->AltBody = 'This is a plain-text message body';
        //Attach an image file
        //        $mail->addAttachment('images/phpmailer_mini.png');
        //send the message, check for errors
        if (!$mail->send()) {
            return "Mailer Error: " . $mail->ErrorInfo;
        } else {
            return "Message sent!";
            //Section 2: IMAP
            //Uncomment these to save your message in the 'Sent Mail' folder.
            #if (save_mail($mail)) {
            #    echo "Message saved!";
            #}
        }

        return new Response();

    }

    /*
     * 过滤字符串
     */
    function strFilter($str){
        $str = str_replace('`', '', $str);
        $str = str_replace('·', '', $str);
        $str = str_replace('~', '', $str);
        $str = str_replace('!', '', $str);
        $str = str_replace('！', '', $str);
        $str = str_replace('@', '', $str);
        $str = str_replace('#', '', $str);
        $str = str_replace('$', '', $str);
        $str = str_replace('￥', '', $str);
        $str = str_replace('%', '', $str);
        $str = str_replace('^', '', $str);
        $str = str_replace('……', '', $str);
        $str = str_replace('&', '', $str);
        $str = str_replace('*', '', $str);
        $str = str_replace('(', '', $str);
        $str = str_replace(')', '', $str);
        $str = str_replace('（', '', $str);
        $str = str_replace('）', '', $str);
        $str = str_replace('-', '', $str);
        $str = str_replace('_', '', $str);
        $str = str_replace('——', '', $str);
        $str = str_replace('+', '', $str);
        $str = str_replace('=', '', $str);
        $str = str_replace('|', '', $str);
        $str = str_replace('\\', '', $str);
        $str = str_replace('[', '', $str);
        $str = str_replace(']', '', $str);
        $str = str_replace('【', '', $str);
        $str = str_replace('】', '', $str);
        $str = str_replace('{', '', $str);
        $str = str_replace('}', '', $str);
        $str = str_replace(';', '', $str);
        $str = str_replace('；', '', $str);
        $str = str_replace(':', '', $str);
        $str = str_replace('：', '', $str);
        $str = str_replace('\'', '', $str);
        $str = str_replace('"', '', $str);
        $str = str_replace('“', '', $str);
        $str = str_replace('”', '', $str);
        $str = str_replace(',', '', $str);
        $str = str_replace('，', '', $str);
        $str = str_replace('<', '', $str);
        $str = str_replace('>', '', $str);
        $str = str_replace('《', '', $str);
        $str = str_replace('》', '', $str);
        $str = str_replace('.', '', $str);
        $str = str_replace('。', '', $str);
        $str = str_replace('/', '', $str);
        $str = str_replace('、', '', $str);
        $str = str_replace('?', '', $str);
        $str = str_replace('？', '', $str);
        return trim($str);
    }

    /*
     * 导入转化成日期格式
     */
    function excelTime($days, $time=false){
        if(is_numeric($days)){
            //based on 1900-1-1
            $jd = GregorianToJD(1, 1, 1970);
            $gregorian = JDToGregorian($jd+intval($days)-25569);
            $myDate = explode('/',$gregorian);
            $myDateStr = str_pad($myDate[2],4,'0', STR_PAD_LEFT)
                ."-".str_pad($myDate[0],2,'0', STR_PAD_LEFT)
                ."-".str_pad($myDate[1],2,'0', STR_PAD_LEFT)
                .($time?" 00:00:00":'');
            return $myDateStr;
        }
        return $days;
    }

    /*
    * 方法 isDate
    * 功能 判断日期格式是否正确
    * 参数 $str 日期字符串
    $format 日期格式
    * 返回 无
    */
    function is_Date($str,$format='Y-m-d'){
        $unixTime_1=strtotime($str);
        if(!is_numeric($unixTime_1)) return false; //如果不是数字格式，则直接返回
        $checkDate=date($format,$unixTime_1);
        $unixTime_2=strtotime($checkDate);
        if($unixTime_1==$unixTime_2){
            return true;
        }else{
            return false;
        }
    }


}